package com.starsea.book.ui.newpage.utils

import android.text.SpannableString
import android.text.Spanned
import android.text.TextUtils
import android.text.style.ForegroundColorSpan
import java.util.regex.Matcher
import java.util.regex.Pattern

/**
 * @author Lee
 * @createTime 2024-01-23 10 GMT+8
 * @desc :
 */
object KeywordUtil {


    fun matchSearchTitle(color: Int, text: String, keyWord: String): SpannableString {

        var keyWord = keyWord
        var text = text
        var s = SpannableString(text)

        keyWord = escapeExprSpecialWord(keyWord)
        text = escapeExprSpecialWord(text)

        if (text.contains(keyWord) && !TextUtils.isEmpty(keyWord)) {

            try {
                val p: Pattern = Pattern.compile(keyWord)
                val m: Matcher = p.matcher(s)
                while (m.find()) {
                    val start: Int = m.start()
                    val end: Int = m.end()
                    s.setSpan(
                        ForegroundColorSpan(color),
                        start,
                        end,
                        Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
                    )
                }
            } catch (e: Exception) {

            }
        }

        return s

    }

    fun escapeExprSpecialWord(keyWord: String): String {
        var keyWord = keyWord
        if (!TextUtils.isEmpty(keyWord)) {
            val fbsArr =
                arrayOf("\\", "$", "(", ")", "*", "+", ".", "[", "]", "?", "^", "{", "}", "|")

            for (key in fbsArr) {
                if (keyWord.contains(key)) {
                    keyWord = keyWord.replace(key, "\\" + key)
                }
            }
        }
        return keyWord
    }

}